package com.sinopec.scandevice.view

import android.Manifest
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.os.Build
import android.os.Bundle
import android.widget.LinearLayout
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.jakewharton.rxbinding3.view.clicks
import com.sinopec.basemodule.BaseApplication
import com.sinopec.basemodule.base.BaseActivity
import com.sinopec.basemodule.base.BasePresenter
import com.sinopec.basemodule.base.CustomToolbar
import com.sinopec.basemodule.utils.ARouterManagerUtils
import com.sinopec.basemodule.utils.kotlin.dp2px
import com.sinopec.basemodule.utils.kotlin.parseInt
import com.sinopec.iuhf.IUHFSettings
import com.sinopec.scandevice.R
import com.sinopec.yelofixedreader.uhf.settings.TimeSettings
import com.sinopec.yelofixedreader.uhf.uhfdi.IUHFHelperDi
import com.sinopec.yelofixedreader.uhf.uhfdi.invoke
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.subjects.PublishSubject
import kotlinx.android.synthetic.main.activity_set.*
import kotlinx.coroutines.delay
import java.util.concurrent.TimeUnit
import kotlin.math.roundToInt

/**
 * @author lwj
 * @ClassName: SetActivity
 * @Description: 设置界面
 */
@Route(path = ARouterManagerUtils.GOTO_LM_SET_ACTIVITY)
class SetActivity : BaseActivity<BasePresenter>() {

    //进度条
    private val mPs = PublishSubject.create<Int>()

    val uhfDi = IUHFHelperDi()
    private val uhf: IUHFSettings =
        uhfDi.settings(IUHFHelperDi.Device.current, uhfDi(this, IUHFHelperDi.Device.current))

    override fun getContentView(): Int {
        return R.layout.activity_set
    }

    override fun configToolbar(rToolbar: CustomToolbar) {
        //配置标题
        rToolbar.setToolbarVisible(false)
    }

    override fun initView(savedInstanceState: Bundle?) {
        initPowerObservable()
        //初始化功率设置
        initSeekBar()
        val userInfo = BaseApplication.getInstance().userManager.user
        //设备id
        tv_device_id.text = userInfo.deviceId
        //仓库
        tv_warehouse.text = userInfo.stockWarehouseName
        //登录用户
        tv_name.text = userInfo.userAccount


        //批次读取时间
        et_count.setText(TimeSettings.readTime.toString())
        et_count.setModule(0, 20.0) {
        }

        //批次间隔时间
        et_second.setText(TimeSettings.divideTime.toString())
        et_second.setModule(0, 20.0) {
        }

        //是否叉车模式
        switch_model.isChecked = TimeSettings.isForkliftMode
    }

    override fun initEvent() {
        super.initEvent()

        /**
         * 保存
         */
        addDisposable(ll_save.clicks()
            .throttleFirst(1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                //批次读取时间
                val etCount = et_count.text.toString()
                if (etCount.parseInt() <= 0) {
                    showMessage("批次读取时间最小为1")
                    return@subscribe
                }
                //批次间隔时间
                val etSecond = et_second.text.toString()
                if (etSecond.parseInt() <= 0) {
                    showMessage("批次间隔时间最小为1")
                    return@subscribe
                }
                TimeSettings.readTime = etCount.parseInt()
                TimeSettings.divideTime = etSecond.parseInt()
                TimeSettings.isForkliftMode = switch_model.isChecked
                lifecycleScope.launchWhenCreated {
                    uhf.pow.set(seek_bar.progress)
                    finish()
                }

            })
    }

    /**
     * 功率设置
     */
    private fun initPowerObservable() {
        addDisposable(mPs.debounce(500, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe { pow: Int? ->
                //保存功率
                //setting.save(pow, mHintSingSwitch.isChecked())
            })
    }

    private fun checkReadWritePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 0)
            }
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
            }
        }
    }

    /**
     *  初始化SeekBar
     */
    private fun initSeekBar() {
        val bitmap = BitmapFactory.decodeResource(resources, R.drawable.ic_rfid_sb)
        val newBitmap = Bitmap.createScaledBitmap(bitmap, 30.dp2px(), 30.dp2px(), true)
        val thumb = BitmapDrawable(
            resources, newBitmap
        )
        checkReadWritePermission()
        seek_bar.thumb = thumb
        lifecycleScope.launchWhenCreated {
            delay(2000)
            seek_bar.progress = uhf.pow.get()
        }
        val layoutParams = seek_bar_hint_tv.layoutParams as LinearLayout.LayoutParams
        seek_bar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                val value: Double = seek_bar.getWidth().toFloat() / 30.0 * 0.75.toFloat()
                val moveStep = value.roundToInt()
                layoutParams.leftMargin = (progress * moveStep).toInt()
                seek_bar_hint_tv.layoutParams = layoutParams
                seek_bar_hint_tv.text = progress.toString() + "dBm"
                mPs.onNext(progress)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })
    }
}